package controllers

import (
    "asset-management-go/global"
    "asset-management-go/models"
    "asset-management-go/utils"
    "github.com/gin-gonic/gin"
    "net/http"
)

// Login 登录
func Login(ctx *gin.Context) {
    var input struct {
        Username string `json:"username"`
        Password string `json:"password"`
    }

    if err := ctx.ShouldBindJSON(&input); err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    var user models.User

    // 验证用户名
    if err := global.Mysql.Where("username = ?", input.Username).First(&user).Error; err != nil {
        ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid username or password"})
        return
    }

    // 验证密码
    if !utils.CheckPassword(input.Password, user.Password) {
        ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid username or password"})
        return
    }

    // 获取用户JWT令牌
    token, err := utils.GenerateJWT(user.Username)
    if err != nil {
        ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    ctx.JSON(http.StatusOK, gin.H{"token": token})
}
